package com.example.excelreader.service;

import com.alibaba.excel.EasyExcel;
import com.example.excelreader.dao.ExcelTest;
import com.example.excelreader.dao.ExcelRepository;
import com.example.excelreader.entity.ExcelEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExcelReadService {

    @Autowired
    private ExcelRepository repository;

    public int read(InputStream inputStream) {
        // 通过EasyExcel读取文件，excel的title对应ExcelEntity的字段名
        List<ExcelEntity> excel = EasyExcel.read(inputStream).head(ExcelEntity.class).sheet().doReadSync();
        List<ExcelTest> pos = excel.stream().map(this::convert).collect(Collectors.toList());
        // 存到db中
        repository.saveAll(pos);
        return pos.size();
    }

    private ExcelTest convert(ExcelEntity excelEntity){
        ExcelTest po = new ExcelTest();
        // 这里会按照字段名称和属性一一把entity和po对应的值复制过去
        BeanUtils.copyProperties(excelEntity, po);
        po.setTest_2(excelEntity.getTest2());
        po.setTestOne(excelEntity.getTestOne());
        return po;
    }


}
